package com.loie.xcx.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.loie.xcx.mapper.IwInstanceMapper;
import com.loie.xcx.mapper.IwTaskMapper;
import com.loie.xcx.mapper.SqlMapper;
import com.loie.xcx.model.bo.IwInstance;
import com.loie.xcx.model.bo.IwTask;
import com.loie.xcx.model.bo.UserInfoBO;
import com.loie.xcx.model.dto.*;
import com.loie.xcx.service.IwInstanceService;
import com.loie.xcx.util.DateUtil;
import com.loie.xcx.util.GetFlowModule_field_util;
import com.loie.xcx.util.Workflow;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author testjava
 * @Slf4j
 * @since 2023-03-01
 */
@Slf4j
@Service
public class IwInstanceServiceImpl extends ServiceImpl<IwInstanceMapper, IwInstance> implements IwInstanceService {


    @Autowired
    private IwTaskMapper iwTaskMapper;
    @Autowired
    private SqlMapper sqlMapper;


    @Autowired
    GetFlowModule_field_util getFlowModule_field_util;

    private static final Logger logapp = LoggerFactory.getLogger("applog");

    @Override
    public String flow_agree(String recordid, String modulename, String openId, Boolean isagree, String... arr) throws Exception {
        String username = "";
        String content = "";
        String userid = "";
        String datestr = "";
        if (arr.length > 0)
            username = arr[0];
        if (arr.length > 1) content = arr[1];
        if (arr.length > 2) datestr = arr[2];
        UserInfoBO userInfoBO = sqlMapper.get_userid_openid(openId);
        userid = userInfoBO.getUserId();
        username = userInfoBO.getUserName();
        if (StringUtils.isEmpty(userid)) {
            return "用户:" + userInfoBO.getUserName() + "不存在";
        }

        QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
//        String recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
//        String modulename = "赊销额度申请";
        wrapper.select(" * ");
        wrapper.eq("RecordID", recordid)
                .eq("Module", modulename)
                .eq("Deleted", 0)
                .isNull("FinishTime")
                .ne("State", 2);

        //.orderByDesc("serialid");
        Integer flowupdatecount = 0;
        Integer taskinscount = 0;
        Integer taskupdatecount = 0;
        Integer updatemaintablecount = 0;
        String save_result = "";
        String unitname = "";

        Long count = baseMapper.selectCount(wrapper);
        List<IwFlow> iwFlowList1 = new ArrayList<IwFlow>();
        Map<String, Object> params = new HashMap<>();
        if (count > 0) {
            wrapper.clear();
            wrapper.select("top 1 * ");
            wrapper.eq("RecordID", recordid)
                    .eq("Module", modulename)
                    .eq("Deleted", 0)
                    .isNull("FinishTime")
                    .ne("State", 2);

            wrapper.orderByDesc("serialid");
            IwInstance iwInstance = baseMapper.selectOne(wrapper);
            QueryWrapper<IwTask> taskQueryWrapper = new QueryWrapper<>();
            taskQueryWrapper.select("top 1 * ");
            taskQueryWrapper.eq("InstanceID", iwInstance.getInstanceID());
            taskQueryWrapper.eq("Deleted", 0);

            taskQueryWrapper.orderByDesc("serialid");
            List<IwTask> iwTaskList = iwTaskMapper.selectList(taskQueryWrapper);
            if (iwTaskList.size() == 0) {
                log.info(save_result);
                save_result = "无相应的审批任务";
                return save_result;

            }
            IwTask iwTask = iwTaskList.get(0);
            if (!StringUtils.isEmpty(userid) &&
                    !iwTask.getExecutor().equals(userid)) {
                return username + "没有审批任务";

            }
            String xml = iwInstance.getFlowData();
            //System.out.println(xml);
            Document doc = null;
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
            params.clear();
            params.put("Content", content);
            Workflow.module_arraylist = Workflow.getmodle_fieldlist(modulename);
            Date spectime = new Date();
            if (!StringUtils.isEmpty(datestr))
                spectime = DateUtil.formatdatetime(datestr);
            else
                spectime = new Date();
            getFlowModule_field_util.ative_elemnt(recordid, modulename, content, rootElt, isagree, params, spectime);
            Document document = DocumentHelper.parseText(rootElt.asXML());
            if (!StringUtils.isEmpty(params) && params.size() > 0) {
                iwInstance.setCurrentFlowActivity(params.get("CurrentFlowActivity").toString());
                iwInstance.setLastFlowActivity(params.get("LastFlowActivity").toString());
                //iwInstance.setTaskid(params.get("TaskID").toString());
                if (params.get("CurrentFlowActivity").toString().equals("已结束")) {
                    iwInstance.setFinishTime(DateUtil.StringTodatetime((params.get("FinishTime").toString())));
                    iwInstance.setState(2);
                }

                unitname = params.get("CurrentFlowActivity").toString();
                iwInstance.setFlowData(document.asXML());
                flowupdatecount = baseMapper.update_flowdata(iwInstance);
                //System.out.println("流程表更新" + Integer.valueOf(flowupdatecount));
                //System.out.println(count);
                System.out.println(params);
                if (!StringUtils.isEmpty(iwTask)) {
                    iwTask.setFinishTime(DateUtil.StringTodatetime((params.get("FinishTime").toString())));
                    iwTask.setState(Integer.valueOf(params.get("State").toString()));
                    iwTask.setContent(params.get("Content").toString());
                    taskupdatecount = iwTaskMapper.update_flowdata(iwTask);
                    System.out.println("任务表更新" + Integer.valueOf(taskupdatecount));
                    if (!params.containsKey("endflow")) {
                        iwTask.setSerialID(null);
                        iwTask.setTaskID(params.get("TaskID").toString());
                        iwTask.setUnitName(params.get("unitname").toString());
                        iwTask.setExecutor(params.get("Executor").toString());
                        iwTask.setState(0);
                        iwTask.setFinishTime(null);
                        iwTask.setContent(null);
                        iwTask.setReceiveTime(DateUtil.StringTodatetime((params.get("ReceiveTime").toString())));
                        iwTask.setSubject(params.get("subject").toString());
                        iwTask.setDeleted(false);
                        taskinscount = iwTaskMapper.insert(iwTask);
                        System.out.println("任务表新增" + Integer.valueOf(taskinscount));
                    } else {
                        System.out.println(content);
                        System.out.println(iwTask.getUnitName());
                        updatemaintablecount = getFlowModule_field_util.DoAfterFinish(modulename, recordid, content,iwTask.getUnitName());
                        System.out.println(updatemaintablecount);
                    }
                }
            }
            save_result = "当前审批节点:" + unitname + "/流程表更新:" + String.valueOf(flowupdatecount) + "/任务表更新:" + String.valueOf(taskupdatecount) + "/任务表新增:" + String.valueOf(taskinscount) + "/更新" + modulename + "状态:" + String.valueOf(updatemaintablecount);


        } else
            save_result = "当前无审批记录，请确认流程是否启动或已完成";

        logapp.info(save_result);
        return save_result;
    }

    @Override
    public Boolean changeusr(String recordid, String modulename, String olduser, String newuser) throws DocumentException {
        Boolean isupdate = false;
        String olduserid = sqlMapper.get_userid(olduser);
        String newuserid = sqlMapper.get_userid(newuser);
        if (!StringUtils.isEmpty(olduserid) & !StringUtils.isEmpty(newuserid)) {
            QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
//        String recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
//        String modulename = "赊销额度申请";
            //wrapper.select("top 1 * ");
            wrapper.eq("RecordID", recordid)
                    .eq("Module", modulename);
            List<IwInstance> iwInstanceList = baseMapper.selectList(wrapper);
            for (IwInstance iwInstance : iwInstanceList) {
                String xml = iwInstance.getFlowData();
                //System.out.println(xml);
                Document doc = null;
                doc = DocumentHelper.parseText(xml);
                Element rootElt = doc.getRootElement();
                Boolean ischange = getFlowModule_field_util.changeusr(rootElt, olduserid, newuserid);
                if (ischange) {
                    Document document = DocumentHelper.parseText(rootElt.asXML());
                    iwInstance.setFlowData(document.asXML());
                    String instanceid = iwInstance.getInstanceID();
                    int updatecout = baseMapper.update_onlyflowdata(iwInstance);
                    System.out.println(instanceid);
                    //UpdateWrapper<IwTask> updateWrapper = new UpdateWrapper<>();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("newuserid", newuserid);
                    map.put("olduserid", olduserid);
                    map.put("instanceid", instanceid);

                    iwTaskMapper.update_executor(map);
                    if (updatecout > 0)
                        isupdate = true;


                }


            }
        }
        return isupdate;
    }

    @Override
    public List<IwInstanceDTO> getflowlist(List<String> moudlelist, IwinstanceQueryDTO iwinstanceQueryDTO) {
        return baseMapper.getflowlist(moudlelist, iwinstanceQueryDTO);
    }

    @Override
    public List<IwInstanceDTO> getflowcompletedlist(List<String> moudlelist, IwinstanceQueryDTO iwinstanceQueryDTO) {
        return baseMapper.getflowcompletedlist(moudlelist, iwinstanceQueryDTO);
    }

    @Override
    public Integer getflowListTotal(List<String> moudlelist, IwinstanceQueryDTO iwinstanceQueryDTO) {
        return baseMapper.getflowListTotal(moudlelist, iwinstanceQueryDTO);
    }

    @Override
    public Integer getflowcompletedTotal(List<String> moudlelist, IwinstanceQueryDTO iwinstanceQueryDTO) {
        return baseMapper.getflowcompletedTotal(moudlelist, iwinstanceQueryDTO);
    }

    @Override
    public List<Moduletotal> getflowModuleListTotal(List<String> moudlelist, IwinstanceQueryDTO iwinstanceQueryDTO) {
        return baseMapper.getflowModuleListTotal(moudlelist, iwinstanceQueryDTO);
    }

    @Override
    public List<IwTaskDTO> getflowTaskList(IwinstanceQueryDTO iwinstanceQueryDTO) {
        return baseMapper.getflowTaskList(iwinstanceQueryDTO);
    }


}
